﻿using Furion;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.JsonSerialization;
using iemtm.WeChat.Application.UserCenter;
using iemtm.WeChat.Core;
using iemtm.WeChat.Core.Extension;
using iemtm.WeChat.Core.Extension.Helper;
using iemtm.WeChat.Core.Managers;
using iemtm.WeChat.Core.Util;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iemtm.WeChat.Application.SystemCenter
{
    /// <summary>
    /// 工单管理
    /// </summary>
    public class AnnouceAppService : IAnnouceAppService, IDynamicApiController, ITransient
    {
        private readonly IWorkManager _workManager;
        private readonly IUserManager _userManager;
        //private readonly IGeneratorManager _generatorManager;
        private readonly IInfoManager _infoManager;

        public AnnouceAppService(IWorkManager workManager
            , IUserManager userManager
            // , IGeneratorManager generatorManager
            , IInfoManager infoManager
            )
        {
            _workManager = workManager;
            _userManager = userManager;
            //  _generatorManager = generatorManager;
            _infoManager = infoManager;
        }

        #region 工单

        /// <summary>
        /// 获取工单列表（分页）
        /// </summary>
        /// <param name="times">全部0 一周7 半月15 本月30</param>
        /// <param name="pagesize">每页多少数据，默认50</param>
        /// <param name="topNum">配合sql语句</param>
        /// <param name="menuIndex">页面tab选项 0：待接单 1：执行中 2：已结单 3：已审核</param>
        /// <param name="paraStr">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetAnnListByPage(int times = 0, int pagesize = 50, int topNum = 1, int menuIndex = 0, string paraStr = "")
        {
            string notExeDtSql = "", exeingDtSql = "", completeDtSql = "", audiuDtSql = "";
            var loginfo = _workManager.CurrentUser;
            var whereStr = 0;
            if (paraStr != "" && paraStr != null)
                whereStr = 1;//搜索框有内容
            var whereStr2 = (whereStr == 1) ? (" and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : "";
            if (times == 1)//今日
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ");
            }
            else if (times == -1)//昨天
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))+' 23:59:59')");
            }
            else if (times == 7)//7天内
            {
                //whereStr2 =  " and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ";
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ");
            }

            else if (times == 30)//本月
            {
                //whereStr2 = " and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') ";
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') ");
            }
            var isAudit = loginfo.PerUrls.Contains("/Gen/AnnounceTeleAudit/Audit");
            string sqlstr = "";
            string notExeDtsqlstr = "";
            //未执行的
            DataTable notExeDt = new DataTable(); ;
            //获取执行中的通知单
            DataTable exeingDt = new DataTable(); ;
            //获取执行完成的通知单
            DataTable completeDt = new DataTable(); ;
            //获取审核通过或未通过的通知单
            DataTable audiuDt = new DataTable(); ;
            var isOperaterView = false;
            string TopageWhere = "AND al.AnnounceId < " + topNum + "";
            if (topNum <= 1)
            {
                TopageWhere = "";
            }
            if (isAudit && loginfo.RoleCode != "subadmin")//如果是运营商则只筛选跟他相关的工单
            {
                isOperaterView = true;
                var whereStr1 = "";
                if (loginfo.RoleCode == "ChinaMobileMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 4";
                }
                else if (loginfo.RoleCode == "ChinaUnicomMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 5";
                }
                else if (loginfo.RoleCode == "ChinaTelcomMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 6";
                }
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = " and al.areaCode like '" + loginfo.AreaCode + "%'";


                sqlstr = " select top " + pagesize + " al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation,al.GenerationFor," +
                "(select username from UserAccount where usercode = al.AnnouncePerson) as AnnouncePerson,al.AcceptPersonCode,al.AcceptPersonName,al.RegisteredGenset,al.RegisteredAbnormal,al.GenManagePersonPhone," +
                "al.ExecutionDate,AnnounceStatusValue = (select c.DicType from CommType c where c.TabName = 'AnnounceStatus' and c.DicValue =(select top 1 aa.AnnounceStatus from AnnounceAudit aa where aa.AnnounceCode=al.AnnounceCode " + whereStr1 + "))," +
                "AnnounceStatus=(select top 1 aa.AnnounceStatus from AnnounceAudit aa where aa.AnnounceCode=al.AnnounceCode " + whereStr1 + "),aAnnounceId=(select top 1 aa.Id from AnnounceAudit aa where aa.AnnounceCode=al.AnnounceCode " + whereStr1 + ") from AnnounceList al  " +
                "where al.prjcode=" + loginfo.PrjCode + " and al.AnnounceCode in(select distinct aa.AnnounceCode from AnnounceAudit aa where (aa.AnnounceStatus {0} " + whereStr1 + ")  " + filterCompanyCode + "" + whereStr2 + "  " + TopageWhere + " order by al.AnnounceId  DESC";

                //未执行的
                notExeDt = new DataTable();//

                //获取执行中的通知单
                exeingDt = new DataTable();

                //获取执行完成的通知单
                //completeDt = await (string.Format(sqlstr, "=29 or AnnounceStatus=31)")).SqlQueryAsync();
                completeDtSql = string.Format(sqlstr, "=29 or AnnounceStatus=31)");

                //获取审核通过或未通过的通知单
                //audiuDt = await (string.Format(sqlstr, "=30)")).SqlQueryAsync();
                audiuDtSql = string.Format(sqlstr, "=30)");
            }
            else
            {
                isOperaterView = false;
                bool bTurnOrder = loginfo.PerUrls.Contains("/Gen/Announce/UserTurnOrder");
                bool bAllOrder = loginfo.PerUrls.Contains("/api/appservice/GetAnnounceLists");
                string areaFilterStr = iemtm.WeChat.Core.Util.Common.GetAreaFilterStrWx(loginfo.AreaCode, loginfo);
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = commonFilterJustByArea ? areaFilterStr.Replace("(", " where al.").Replace(")", " ") : " where al.AcceptCompanyCode like '" + loginfo.CompanyCode + "%' ";


                sqlstr = "select distinct top " + pagesize + "'" + (bTurnOrder) + "' as bTurnOrder,al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation," +
                   "(select username from UserAccount where usercode=al.AnnouncePerson) as AnnouncePerson,al.AcceptPersonCode,al.AcceptPersonName,al.RegisteredGenset,al.RegisteredAbnormal," +
                   "al.GenManagePersonPhone,al.ExecutionDate as ExecutionDate,AnnounceStatusValue=(select c.DicType from CommType c where c.TabName='AnnounceStatus' and c.DicValue=al.AnnounceStatus)," +
                                 "al.AnnounceStatus from AnnounceList al " + (bAllOrder ? filterCompanyCode : "where (al.AcceptPersonCode='" + loginfo.UserCode + "')") + " and (al.AnnounceStatus{0}) " + "" + whereStr2 + " " + TopageWhere + " order by al.AnnounceId DESC";

                string filterIsTieta = commonFilterJustByArea ? "al.AreaCode like '" + loginfo.AreaCode + "%'" : "al.AnnounceCode in (select AnnounceCode from AnnounceCompany where CompanyCode like '" + loginfo.CompanyCode + "%')";

                notExeDtsqlstr = "select distinct top " + pagesize + " al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation," +
             "(select username from UserAccount where usercode=al.AnnouncePerson) as AnnouncePerson,al.AcceptPersonCode,al.AcceptPersonName,al.RegisteredGenset,al.RegisteredAbnormal," +
             "al.GenManagePersonPhone,al.ExecutionDate as ExecutionDate,AnnounceStatusValue=(select c.DicType from CommType c where c.TabName='AnnounceStatus' and c.DicValue=al.AnnounceStatus),al.AnnounceStatus from AnnounceList al where " + filterIsTieta + " and (al.AnnounceStatus={0} " + whereStr2 + " " + TopageWhere + " order by al.AnnounceId DESC";
                //未执行的
                // notExeDt =await (string.Format(notExeDtsqlstr, "20 )")).SqlQueryAsync();
                notExeDtSql = string.Format(notExeDtsqlstr, "20 )");
                //获取执行中的通知单
                //exeingDt = await (string.Format(sqlstr, ">=21 and AnnounceStatus<=28 ")).SqlQueryAsync();
                exeingDtSql = string.Format(sqlstr, ">=21 and AnnounceStatus<=28 ");
                //获取执行完成的通知单
                //completeDt = await (string.Format(sqlstr, "=29 or AnnounceStatus=31")).SqlQueryAsync();
                completeDtSql = string.Format(sqlstr, "=29 or AnnounceStatus=31");
                //获取审核通过或未通过的通知单
                //audiuDt = (string.Format(sqlstr, "=30")).SqlQuery();
                audiuDtSql = string.Format(sqlstr, "=30");

            }
            switch (menuIndex)
            {
                case 0://待接单
                    if (!string.IsNullOrEmpty(notExeDtSql))
                    {
                        notExeDt = await notExeDtSql.SqlQueryAsync();
                    }
                    return new
                    {
                        isAudit = isAudit,
                        isOperaterView = isOperaterView,
                        noExtTotal = notExeDt.Rows.Count,
                        noEx = notExeDt.ToDynamicList()
                    };
                case 1://执行中
                    if (!string.IsNullOrEmpty(exeingDtSql))
                    {
                        exeingDt = await exeingDtSql.SqlQueryAsync();
                    }
                    return new
                    {
                        isAudit = isAudit,
                        isOperaterView = isOperaterView,
                        exingTotal = exeingDt.Rows.Count,
                        exeing = exeingDt.ToDynamicList()
                    };
                case 2://已结单
                    if (!string.IsNullOrEmpty(completeDtSql))
                    {
                        completeDt = await completeDtSql.SqlQueryAsync();
                    }
                    return new
                    {
                        isAudit = isAudit,
                        isOperaterView = isOperaterView,
                        completelyTotal = completeDt.Rows.Count,
                        completely = completeDt.ToDynamicList()
                    };
                case 3://已审核
                    if (!string.IsNullOrEmpty(audiuDtSql))
                    {
                        audiuDt = await audiuDtSql.SqlQueryAsync();
                    }
                    return new
                    {
                        isAudit = isAudit,
                        isOperaterView = isOperaterView,
                        audiuTotal = audiuDt.Rows.Count,
                        audiu = audiuDt.ToDynamicList()
                    };
                default://返回空数据
                    return new
                    {
                        isAudit = isAudit,
                        isOperaterView = isOperaterView,
                        audiuTotal = 0,
                        audiu = "[]"
                    };
            }
        }

        /// <summary>
        /// 工单列表统计数量
        /// </summary>
        /// <param name="times"></param>
        /// <param name="paraStr"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetAnnCount(int times = 0, string paraStr = "")
        {

            var loginfo = _workManager.CurrentUser;
            if (loginfo == null)
                return null;
            var whereStr = 0;
            if (paraStr != "" && paraStr != null)
                whereStr = 1;//搜索框有内容
            var whereStr2 = (whereStr == 1) ? (" and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : "";
            if (times == 1)//今天
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ");
            }
            else if (times == -1)//昨天
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))+' 23:59:59') ");
            }
            else if (times == 7)//7天内
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ");

            }

            else if (times == 30)//本月
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') ");

            }
            var isAudit = loginfo.PerUrls.Contains("/Gen/AnnounceTeleAudit/Audit");
            string sqlstr = "";
            string notExeDtsqlstr = "";
            //未执行的
            DataTable notExeDt;
            //获取执行中的通知单
            DataTable exeingDt;
            //获取执行完成的通知单
            DataTable completeDt;
            //获取审核通过或未通过的通知单
            DataTable audiuDt;
            var isOperaterView = false;
            if (isAudit && loginfo.RoleCode != "subadmin")//如果是运营商则只筛选跟他相关的工单
            {
                isOperaterView = true;
                var whereStr1 = "";
                if (loginfo.RoleCode == "ChinaMobileMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 4";
                }
                else if (loginfo.RoleCode == "ChinaUnicomMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 5";
                }
                else if (loginfo.RoleCode == "ChinaTelcomMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 6";
                }
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = " and al.areaCode like '" + loginfo.AreaCode + "%'";
                sqlstr = " SELECT COUNT(*) AS	count FROM (select al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation,al.GenerationFor," +
                          "(select username from UserAccount where usercode = al.AnnouncePerson) as AnnouncePerson,al.AcceptPersonCode,al.AcceptPersonName,al.RegisteredGenset,al.RegisteredAbnormal,al.GenManagePersonPhone," +
                          "al.ExecutionDate,AnnounceStatusValue = (select c.DicType from CommType c where c.TabName = 'AnnounceStatus' and c.DicValue =(select top 1 aa.AnnounceStatus from AnnounceAudit aa where aa.AnnounceCode=al.AnnounceCode " + whereStr1 + "))," +
                          "AnnounceStatus=(select top 1 aa.AnnounceStatus from AnnounceAudit aa where aa.AnnounceCode=al.AnnounceCode " + whereStr1 + "),aAnnounceId=(select top 1 aa.Id from AnnounceAudit aa where aa.AnnounceCode=al.AnnounceCode " + whereStr1 + ") from AnnounceList al  " +
                          "where al.prjcode=" + loginfo.PrjCode + " and al.AnnounceCode in(select distinct aa.AnnounceCode from AnnounceAudit aa where (aa.AnnounceStatus {0} " + whereStr1 + ")  " + filterCompanyCode + "" + whereStr2 + " ) AS T";

                //未执行的
                //notExeDt = new DataTable();
                notExeDt = ("SELECT COUNT(AnnounceId) AS count FROM dbo.AnnounceList WHERE AnnounceStatus=1000").SqlQuery();//赋值0
                //获取执行中的通知单
                //exeingDt = new DataTable();
                exeingDt = ("SELECT COUNT(AnnounceId) AS count FROM dbo.AnnounceList WHERE AnnounceStatus=1000").SqlQuery();//赋值0

                //获取执行完成的通知单
                completeDt = (string.Format(sqlstr, "=29 or AnnounceStatus=31)")).SqlQuery();

                //获取审核通过或未通过的通知单
                audiuDt = (string.Format(sqlstr, "=30)")).SqlQuery();
            }
            else
            {
                isOperaterView = false;
                bool bTurnOrder = loginfo.PerUrls.Contains("/Gen/Announce/UserTurnOrder");
                bool bAllOrder = loginfo.PerUrls.Contains("/api/appservice/GetAnnounceLists");
                string areaFilterStr = iemtm.WeChat.Core.Util.Common.GetAreaFilterStrWx(loginfo.AreaCode, loginfo);
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = commonFilterJustByArea ? areaFilterStr.Replace("(", " where al.").Replace(")", " ") : " where al.AcceptCompanyCode like '" + loginfo.CompanyCode + "%' ";

                sqlstr = "SELECT COUNT(*) AS	count FROM (select distinct '" + (bTurnOrder) + "' as bTurnOrder,al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation," +
                    "(select username from UserAccount where usercode=al.AnnouncePerson) as AnnouncePerson,al.AcceptPersonCode,al.AcceptPersonName,al.RegisteredGenset,al.RegisteredAbnormal," +
                    "al.GenManagePersonPhone,al.CreateDate as ExecutionDate,AnnounceStatusValue=(select c.DicType from CommType c where c.TabName='AnnounceStatus' and c.DicValue=al.AnnounceStatus)," +
                                  "al.AnnounceStatus from AnnounceList al " + (bAllOrder ? filterCompanyCode : "where (al.AcceptPersonCode='" + loginfo.UserCode + "')") + " and (al.AnnounceStatus{0}) " + "" + whereStr2 + "  ) AS T";
                string filterIsTieta = commonFilterJustByArea ? "al.AreaCode like '" + loginfo.AreaCode + "%'" : "al.AnnounceCode in (select AnnounceCode from AnnounceCompany where CompanyCode like '" + loginfo.CompanyCode + "%')";
                notExeDtsqlstr = "SELECT COUNT(*) AS	count FROM (select distinct al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation," +
             "(select username from UserAccount where usercode=al.AnnouncePerson) as AnnouncePerson,al.AcceptPersonCode,al.AcceptPersonName,al.RegisteredGenset,al.RegisteredAbnormal," +
             "al.GenManagePersonPhone,al.CreateDate as ExecutionDate,AnnounceStatusValue=(select c.DicType from CommType c where c.TabName='AnnounceStatus' and c.DicValue=al.AnnounceStatus),al.AnnounceStatus from AnnounceList al where " + filterIsTieta + " and (al.AnnounceStatus={0} " + whereStr2 + " ) AS T";
                //未执行的
                notExeDt = await (string.Format(notExeDtsqlstr, "20 )")).SqlQueryAsync();

                //获取执行中的通知单
                exeingDt = await (string.Format(sqlstr, ">=21 and AnnounceStatus<=28 ")).SqlQueryAsync();

                //获取执行完成的通知单
                completeDt = await (string.Format(sqlstr, "=29 or AnnounceStatus=31")).SqlQueryAsync();

                //获取审核通过或未通过的通知单
                audiuDt = await (string.Format(sqlstr, "=30")).SqlQueryAsync();

            }


            return new
            {
                isAudit = isAudit,
                isOperaterView = isOperaterView,
                noExtTotal = notExeDt.Rows[0]["count"],
                //noEx = DBCommon.ToDynamic(notExeDt),
                exingTotal = exeingDt.Rows[0]["count"],
                //exeing = DBCommon.ToDynamic(exeingDt),
                completelyTotal = completeDt.Rows[0]["count"],
                //completely = DBCommon.ToDynamic(completeDt),
                audiuTotal = audiuDt.Rows[0]["count"],
                //audiu = DBCommon.ToDynamic(audiuDt)
            };
        }

        /// <summary>
        /// 查询油机和采集器信息-签到扫描事件
        /// </summary>
        /// <param name="type"></param>
        /// <param name="paraStr"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        [NonUnify]
        public dynamic GetGenSetOrDtuidInfo(string type, string paraStr)
        {

            if (type == "G")
            {
                var genInfoG = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(c => c.GensetNum == paraStr.Trim());

                if (genInfoG != null)
                {
                    return (new  { Code = 1, Result = genInfoG });
                }
                else
                {
                    return (new { Code = 0, Result = "没找到油机" });
                }
            }
            if (type == "C")
            {
                var genInfoC = MemoryEntity.cBuffColl.All.Values.FirstOrDefault(c => c.DTUID == paraStr.Trim());

                if (genInfoC != null)
                {
                    return new { Code = 1, Result = genInfoC };
                }
                else
                {
                    return (new { Code = 0, Result = "没找到采集器" });
                }
            }
            
            return (new  { Code = 0, Result = "" });
        }

        /// <summary>
        /// 用户处理通知单(接单,签到,扫码油机)
        /// </summary>
        /// <param name="annouceCode"></param>
        /// <param name="AnnounceStatus"></param>
        /// <param name="longitude"></param>
        /// <param name="latitude"></param>
        /// <param name="gensetNum"></param>
        /// <param name="registeredDtuId"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic>UserProcessAnnouce(string annouceCode, string AnnounceStatus, double longitude, double latitude, string gensetNum, string generationFor, string registeredDtuId)
        {
            ResultModel result = new ResultModel();
            //先根据用户扫描或者自行修改的油机编号或者采集器编号进行动态绑定Generator表
            ResultModel resEdit =await EditGenDtuid(gensetNum, registeredDtuId);
            if (resEdit.Code == 0 || resEdit.Code == 2)//绑定有错误，提示
            {
                result = resEdit;
            }
            else if (resEdit.Code == 1 || resEdit.Code == 3)//绑定没错误，进入下一步操作
            {
                //先判断是否结束之前工单
                result =await CheckGenIsBindAnnounce(registeredDtuId);
                if (result.Code == 1)
                {
                    if (AnnounceStatus == "21")//待绑定
                    {
                        //判断是否接线成功
                        //bool isConnection = IsConnection($"http://47.107.245.139:9083/api/Webapi561/IsWiringOK?id={registeredDtuId}");
                        bool isConnection = true;
                        if (isConnection)
                        {
                            //转百度经纬度
                            var gcj02gps = maptransform.wgs84togcj02(longitude, latitude);//GPS先转火星坐标
                            var baidugps = maptransform.gcj02tobd09(gcj02gps[0], gcj02gps[1]);//火星转百度

                            //var baiduGps = GpsConvertToBaiduGps.CovertTo(latitude.ToString(), longitude.ToString());//转百度经纬度
                            //进行签到操作
                            //var geninfo = GeneratorList.getAll().FirstOrDefault(c => c.GensetNum == gensetNum);
                            var geninfo = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(c => c.GensetNum == gensetNum);
                            //result.Code = UserSignIn(geninfo.GeneratorCode, annouceCode, false, Convert.ToDouble(baiduGps.longitude), Convert.ToDouble(baiduGps.latitude), 100, generationFor, registeredDtuId).Code;
                            result.Code =(await UserSignIn(geninfo.GeneratorCode, annouceCode, false, Convert.ToDouble(baidugps[0]), Convert.ToDouble(baidugps[1]), 100, generationFor, registeredDtuId)).Code;
                            if (result.Code >= 1)
                            {
                                result.Code = 1;
                                result.Result = "绑定成功";

                                try
                                {
                                   

                                    if (!string.IsNullOrEmpty(registeredDtuId))
                                    {
                                        

                                        Generator g = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(u => u.DTUID == registeredDtuId);

                                        if (g != null && g.BOnline != false)
                                        {


                                            List<CodeValuePair> prs = new List<CodeValuePair>();
                                            prs.Add(new CodeValuePair { code = "WORKORDER", value = annouceCode });
                                            string dtuCmd = (from ii in prs select ii.code + ";" + ii.value).ToList().StrListToStr(";");
                                            TcpCommunication.WritePara(dtuCmd, registeredDtuId, 15);
                                        }
                                    }
                                    

                                }
                                catch { }
                            }

                        }
                        else
                        {
                            try
                            {
                                string BindRemark = $"签到不成功,油机编码:{gensetNum},采集器ID:{registeredDtuId}";
                              //  dbContext.Updateable<AnnounceList>().UpdateColumns(it => new AnnounceList() { BindRemark = BindRemark }).Where(it => it.AnnounceCode == annouceCode).ExecuteCommand();
                                var ann=await _infoManager.GetAnnFirstOrDefaultAsync(u => u.AnnounceCode == annouceCode);
                                ann.BindRemark = BindRemark;
                                _infoManager.UpdateAnnUpdateInclude(ann,new[] { nameof(ann.BindRemark)});
                            }
                            catch (Exception e)
                            {

                            }
                            result.Code = 0;
                            result.Result = "绑定失败，检查模块是否在线，接线是否正确！";
                        }

                    }
                    else
                    {
                        if ((await UserOrderBy(annouceCode)).Code == 1)//模拟app进行接单操作，返回成功，进入下一步操作
                        {
                            //判断是否接线成功
                            //bool isConnection = IsConnection($"http://47.107.245.139:9083/api/Webapi561/IsWiringOK?id={registeredDtuId}");
                            bool isConnection = true;
                            if (isConnection)
                            {
                                //转百度经纬度
                                var gcj02gps = maptransform.wgs84togcj02(longitude, latitude);//GPS先转火星坐标
                                var baidugps = maptransform.gcj02tobd09(gcj02gps[0], gcj02gps[1]);//火星转百度

                                //var baiduGps = GpsConvertToBaiduGps.CovertTo(latitude.ToString(), longitude.ToString());//转百度经纬度
                                //进行签到操作
                                //var geninfo = GeneratorList.getAll().FirstOrDefault(c => c.GensetNum == gensetNum);
                                var geninfo = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(c => c.GensetNum == gensetNum);
                                
                                //result.Code = UserSignIn(geninfo.GeneratorCode, annouceCode, false, Convert.ToDouble(baiduGps.longitude), Convert.ToDouble(baiduGps.latitude), 100, generationFor, registeredDtuId).Code;
                                result.Code =(await UserSignIn(geninfo.GeneratorCode, annouceCode, false, Convert.ToDouble(baidugps[0]), Convert.ToDouble(baidugps[1]), 100, generationFor, registeredDtuId)).Code;
                                if (result.Code >= 1)
                                {
                                    result.Code = 1;
                                    result.Result = "绑定成功";

                                    try
                                    {
                                        ////绑定发电记录
                                        //System.Threading.Tasks.Task.Run(() =>
                                        //{
                                        //    AnnounceList ann = BllHelper.GetANNbyAnnCode(annouceCode);
                                        //    if (ann != null)
                                        //        StatusSyncRoute.BindGen2Ann(ann);
                                        //});

                                        ////向模块写入工单号
                                        //System.Threading.Tasks.Task.Run(() =>
                                        // {
                                        if (!string.IsNullOrEmpty(registeredDtuId))
                                        {

                                            Generator g = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(u => u.DTUID == registeredDtuId);

                                            if (g != null && g.BOnline != false)
                                            {

                                                List<CodeValuePair> prs = new List<CodeValuePair>();
                                                prs.Add(new CodeValuePair { code = "WORKORDER", value = annouceCode });
                                                string dtuCmd = (from ii in prs select ii.code + ";" + ii.value).ToList().StrListToStr(";");
                                                 TcpCommunication.WritePara(dtuCmd, registeredDtuId, 15);
                                            }
                                        }
                                       // });

                                    }
                                    catch { }
                                }
                            }
                            else
                            {
                                try
                                {
                                    string BindRemark = $"签到不成功,油机编码:{gensetNum},采集器ID:{registeredDtuId}";
                                    //dbContext.Updateable<AnnounceList>().UpdateColumns(it => new AnnounceList() { BindRemark = BindRemark }).Where(it => it.AnnounceCode == annouceCode).ExecuteCommand();
                                    var ann = await _infoManager.GetAnnFirstOrDefaultAsync(u => u.AnnounceCode == annouceCode);
                                    ann.BindRemark = BindRemark;
                                    _infoManager.UpdateAnnUpdateInclude(ann, new[] { nameof(ann.BindRemark) });
                                }
                                catch (Exception ex)
                                {

                                }
                                result.Code = 0;
                                result.Result = "绑定失败，检查模块是否在线，接线是否正确！";
                            }

                        }
                    }
                }

            }
            return result;
        }


        /// <summary>
        /// 正常回单操作(效果与App保持一致)
        /// </summary>
        /// <param name="annouceCode"></param>
        /// <param name="userCode"></param>
        /// <param name="FinishRemak"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> replyGensetMethod(string annouceCode, string userCode, string FinishRemak)
        {
            ResultModel result = new ResultModel() { Code = 0, Result = "操作失败！" };
            var loginfo = _workManager.CurrentUser;
            if (userCode == null || userCode == "")
                return result;
          
            if (loginfo == null)
                return result;

            // AnnounceList model = dbContext.Queryable<AnnounceList>().First(x => x.AnnounceCode == annouceCode);
            AnnounceList model = await _infoManager.GetAnnFirstOrDefaultAsync(x => x.AnnounceCode == annouceCode);
               
          
            BaseStation bs =await _infoManager.GetBaseStationFirstAsync(x => x.BaseStationCode == model.BaseStationCode);
               

            int preState = -2;
            int.TryParse(model.AnnounceStatus.ToString() != null && model.AnnounceStatus.ToString() != "" ? model.AnnounceStatus.ToString() : "", out preState);

            string strmysql = $"UPDATE dbo.AnnounceList SET	 AnnounceStatus=29,FinishType=1,FinishTime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',FinishRemak='" + FinishRemak + "',PowEveName='' WHERE AnnounceCode='" + annouceCode + "'";
            int count = await (strmysql).SqlNonQueryAsync();
            if (count <= 0)
            {
                result.Result = string.Format("工单{0}操作出错！", annouceCode);
                result.Code = count;
                return result;
            }
            //更新工单操作日志
            AnnounceStateXLog annLog = new AnnounceStateXLog();
            annLog.EventType = 8;//回单
            annLog.AnnounceCode = annouceCode;
            //annLog.CreateTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            annLog.CreateTime = DateTime.Now;
            annLog.CreatePerson = loginfo.UserCode;
            annLog.CreatePersonName = loginfo.UserName;
            annLog.PreState = preState;
            annLog.AuditRemark = FinishRemak;
            annLog.ToState = 29;//已结单
                            
            annLog.FinishType = 1;
            //dbContext.Insertable<AnnounceStateXLog>(annLog).ExecuteCommandAsync();
            await _infoManager.AddAnnounceStateXLog(annLog);
            

            //计费
             await GetPowergenerationDataNotFgw(model.AnnounceCode);

            result.Code = 1;
            result.Result = "操作成功";
            return result;
        }


        /// <summary>
        /// 更换油机接口
        /// </summary>
        /// <param name="annouceCode"></param>
        /// <param name="AnnounceId"></param>
        /// <param name="gensetNum"></param>
        /// <param name="registeredDtuId"></param>
        /// <param name="ChangeReason"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> ChangeAnnGensetMethod(string annouceCode, string AnnounceId, string gensetNum, string registeredDtuId, string ChangeReason)
        {
            ResultModel result = new ResultModel() { Code = 0, Result = "操作失败！" };
            //先根据用户扫描或者自行修改的油机编号或者采集器编号进行动态绑定Generator表
            ResultModel resEdit =await EditGenDtuid(gensetNum, registeredDtuId);
            if (resEdit.Code == 0 || resEdit.Code == 2)//绑定有错误，提示
            {
                result = resEdit;
            }
            else if (resEdit.Code == 1 || resEdit.Code == 3)//绑定没错误，进入下一步操作
            {
                //先判断是否结束之前工单
                result =await CheckGenIsBindAnnounce(registeredDtuId);
                if (result.Code == 1)
                {
                    //找出此工单
                    AnnounceList annModel =await _infoManager.GetAnnFirstOrDefaultAsync(x => x.AnnounceCode == annouceCode);
                    //dbContext.Queryable<AnnounceList>().First(x => x.AnnounceCode == annouceCode);
                    if (annModel != null)
                    {
                        //开通工单的更换权限，添加此条工单的油机绑定数量
                        annModel.IsChangeGenset = true;
                        if (annModel.AnnounceStatus <= 21 || annModel.AnnounceStatus >= 29)
                        {
                            result.Code = 0;
                            result.Result = "工单状态不允许进行续签操作！";
                            return result;
                        }
                        //不可重复绑定
                        //var geninfo = GeneratorList.Frist(c => c.GensetNum == gensetNum);
                        var geninfo = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(c => c.GensetNum == gensetNum);
                        if (annModel.RegisteredGenset == geninfo.GeneratorCode || annModel.RegisteredDtuId == registeredDtuId)
                        {
                            result.Code = 0;
                            result.Result = "工单不允许绑定重复油机！";
                            return result;
                        }
                        //找出更换中间表，若已绑定过，则不允许绑定
                        //List<ChangeAnnGenset> oldReBinList = dbContext.Queryable<ChangeAnnGenset>().Where(x => x.AnnounceId == Convert.ToInt32(AnnounceId) && x.AnnounceCode == annouceCode).ToList();
                        List<ChangeAnnGenset> oldReBinList =await _infoManager.GetChangeAnnGensetListAsync(x => x.AnnounceId == Convert.ToInt32(AnnounceId) && x.AnnounceCode == annouceCode);

                        foreach (var item in oldReBinList)
                        {
                            //var geninfo1 = GeneratorList.Frist(c => c.GensetNum == gensetNum);
                            var geninfo1 = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(c => c.GensetNum == gensetNum);
                            if (item.RegisteredGenset == geninfo.GeneratorCode && item.RegisteredDtuId == registeredDtuId && item.AnnounceCode == annouceCode)
                            {
                                result.Code = 0;
                                result.Result = "工单不允许绑定重复油机！";
                                return result;
                            }
                        }

                        //查询油机状态
                       // var generator = GeneratorList.Frist(c => c.GeneratorCode == gensetNum || c.GensetNum == gensetNum);
                        var generator = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(c => c.GeneratorCode == gensetNum || c.GensetNum == gensetNum);
                        if (generator != null && generator.bRunning==true)
                        {
                            annModel.AnnounceStatus = 24;//发电中
                        }
                      //  int count = dbContext.Updateable<AnnounceList>().UpdateColumns(it => new AnnounceList() { IsChangeGenset = annModel.IsChangeGenset, AnnounceStatus = annModel.AnnounceStatus }).Where(it => it.AnnounceCode == annouceCode).ExecuteCommand();
                        var Ann =await _infoManager.GetAnnFirstOrDefaultAsync(it => it.AnnounceCode == annouceCode);
                        Ann.IsChangeGenset = annModel.IsChangeGenset;
                        Ann.AnnounceStatus = annModel.AnnounceStatus;
                        var updateColumn = new[] { 
                        nameof(Ann.IsChangeGenset ),
                        nameof(Ann.AnnounceStatus ),
                        };
                        var IsUpdateSuccess=_infoManager.UpdateAnnUpdateInclude(Ann, updateColumn);
                        if (IsUpdateSuccess)//更新工单表字段成功
                        {
                            
                            //var geninfo2 = GeneratorList.Frist(c => c.GensetNum == gensetNum);
                            //插入续签油机与采集器到表ChangeAnnGenset
                            ChangeAnnGenset changeBinModel = new ChangeAnnGenset() { AnnounceId = annModel.AnnounceId, AnnounceCode = annModel.AnnounceCode, RegisteredGenset = geninfo.GeneratorCode, RegisteredDtuId = registeredDtuId, ChangeReason = ChangeReason };
                           var IsAddSuccess=await _infoManager.AddChangeAnnGensetAsync(changeBinModel);
                            if (IsAddSuccess)
                            {
                                result.Code = 1;
                                result.Result = "操作成功！";
                                try
                                {
                                    ////绑定发电记录
                                    //System.Threading.Tasks.Task.Run(() =>
                                    //{
                                    //    AnnounceList Ann = BllHelper.GetANNbyAnnCode(AnnounceCode);
                                    //    if (Ann != null)
                                    //        StatusSyncRoute.BindGen2Ann(Ann);
                                    //});

                                    //向模块写入工单号
                                    //System.Threading.Tasks.Task.Run(() =>
                                    //{
                                    //    if (string.IsNullOrEmpty(registeredDtuId)) return;
                                    //    Generator g = GeneratorList.Frist(registeredDtuId);
                                    //    if (g == null || g.BOnline == false)
                                    //        return;
                                    //    List<CodeValuePair> prs = new List<CodeValuePair>();
                                    //    prs.Add(new CodeValuePair { code = "WORKORDER", value = annouceCode });
                                    //    string dtuCmd = CCommon.StrListToStr((from ii in prs select ii.code + ";" + ii.value).ToList(), ";");
                                    //    string Tmp = TcpCommunication.WritePara(dtuCmd, registeredDtuId, 15);
                                    //});

                                    if (!string.IsNullOrEmpty(registeredDtuId))
                                    {
                                        Generator g = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(u => u.DTUID == registeredDtuId);
                                        if (g != null && g.BOnline != false)
                                        {
                                            List<CodeValuePair> prs = new List<CodeValuePair>();
                                            prs.Add(new CodeValuePair { code = "WORKORDER", value = annouceCode });
                                            string dtuCmd = (from ii in prs select ii.code + ";" + ii.value).ToList().StrListToStr(";");
                                            TcpCommunication.WritePara(dtuCmd, registeredDtuId, 15);
                                        }
                                    }
                                    

                                }
                                catch { }
                                return result;
                            }
                        }
                    }
                }

            }

            return result;
        }

        /// <summary>
        /// 正常回单时检查是否绑定发电记录
        /// </summary>
        /// <param name="annouceCode"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        [NonUnify]
        public async  Task<dynamic> IsBindGenRecord(string annouceCode)
        {
            var LoginInfo = _workManager.CurrentUser;
            if (LoginInfo != null)
            {
                var genRecord =await _infoManager.GetAnnounceGenListAsync(a => a.AnnounceCode == annouceCode);
                // dbContext.Queryable<AnnounceGen>().Where(a => a.AnnounceCode == annouceCode).ToList();
                if (genRecord != null && genRecord.Count > 0)
                {
                    return (new ResultModel() { Code = 1, Result = "存在发电记录" });
                }
                else
                {
                    return (new ResultModel() { Code = 0, Result = "未存在发电记录" });
                }
            }
            return (new ResultModel() { Code = 0, Result = "会话过期" });
        }

        /// <summary>
        /// 续签接口
        /// </summary>
        /// <param name="annouceCode"></param>
        /// <param name="AnnounceId"></param>
        /// <param name="gensetNum"></param>
        /// <param name="registeredDtuId"></param>
        /// <returns></returns>
        /// 
        [HttpGet]
        [QueryParameters]
        [NonUnify]
        public async Task<dynamic> ReBinAnnGensetMethod(string annouceCode, string AnnounceId, string gensetNum, string registeredDtuId)
        {
            ResultModel result = new ResultModel() { Code = 0, Result = "操作失败！" };
            //先根据用户扫描或者自行修改的油机编号或者采集器编号进行动态绑定Generator表
            ResultModel resEdit =await EditGenDtuid(gensetNum, registeredDtuId);
            if (resEdit.Code == 0 || resEdit.Code == 2)//绑定有错误，提示
            {
                result = resEdit;
            }
            else if (resEdit.Code == 1 || resEdit.Code == 3)//绑定没错误，进入下一步操作
            {
                //先判断是否结束之前工单
                result =await CheckGenIsBindAnnounce(registeredDtuId);
                if (result.Code == 1)
                {
                    int BinGensetNum = 1;//全局变量 
                                         //找出此工单
                    AnnounceList annModel = await _infoManager.GetAnnFirstOrDefaultAsync(x => x.AnnounceCode == annouceCode);
                        
                    if (annModel != null)
                    {
                        //开通工单的多签权限，添加此条工单的油机绑定数量
                        annModel.IsReBinGenset = true;
                        //当前工单已绑定台数；若操作五台  则限制不允许绑定
                        BinGensetNum = Convert.ToInt32(annModel.BinGensetNum);
                        if (BinGensetNum == 5)
                        {
                            result.Code = 0;
                            result.Result = "已超过工单油机绑定数，不允许续签操作！";
                            return result;
                        }
                        if (annModel.AnnounceStatus <= 21 || annModel.AnnounceStatus >= 29)
                        {
                            result.Code = 0;
                            result.Result = "工单状态不允许进行续签操作！";
                            return result;
                        }
                        //不可重复绑定
                        var geninfo =MemoryEntity.gBuffGen.All.Values.FirstOrDefault(c => c.GensetNum == gensetNum);
           
                        if (annModel.RegisteredGenset == geninfo.GeneratorCode || annModel.RegisteredDtuId == registeredDtuId)
                        {
                            result.Code = 0;
                            result.Result = "工单不允许绑定重复油机！";
                            return result;
                        }
                        //找出多签中间表，若已绑定过，则不允许绑定
                        List<ReBinAnnGenset> oldReBinList = await _infoManager.GetReBinAnnGensetListAsync(x => x.AnnounceId == Convert.ToInt32(AnnounceId) && x.AnnounceCode == annouceCode);

                           
                        foreach (var item in oldReBinList)
                        {
                            var geninfo1 =MemoryEntity.gBuffGen.All.Values.FirstOrDefault(c => c.GensetNum == gensetNum);
                            
                            if (item.RegisteredGenset == geninfo.GeneratorCode && item.RegisteredDtuId == registeredDtuId && item.AnnounceCode == annouceCode)
                            {
                                result.Code = 0;
                                result.Result = "工单不允许绑定重复油机！";
                                return result;
                            }
                        }
                        annModel.BinGensetNum = BinGensetNum + 1;
                        //int count = dbContext.Updateable<AnnounceList>().UpdateColumns(it => new AnnounceList() { IsReBinGenset = annModel.IsReBinGenset, BinGensetNum = annModel.BinGensetNum }).Where(it => it.AnnounceCode == annouceCode).ExecuteCommand();
                        var announceList =await _infoManager.GetAnnFirstOrDefaultAsync(u => u.AnnounceCode == annouceCode);
                        announceList.IsReBinGenset = annModel.IsReBinGenset;
                        announceList.BinGensetNum = annModel.BinGensetNum;
                        string[] upcolumn = new[] {
                         nameof(announceList.IsReBinGenset)
                         , nameof(announceList.BinGensetNum)

                        };
                        var isUpdateSuccess = _infoManager.UpdateAnnUpdateInclude(announceList, upcolumn);
                        if (isUpdateSuccess)//更新工单表字段成功
                        {
                            //var geninfo2 =MemoryEntity.gBuffGen.All.Values.FirstOrDefault(c => c.GensetNum == gensetNum);
                            
                            //插入续签油机与采集器到表ReBinAnnGenset
                            ReBinAnnGenset reBinModel = new ReBinAnnGenset() { AnnounceId = annModel.AnnounceId, AnnounceCode = annModel.AnnounceCode, RegisteredGenset = geninfo.GeneratorCode, RegisteredDtuId = registeredDtuId, BinGensetNum = BinGensetNum + 1 };
                            bool IsAddSuccess = await _infoManager.AddReBinAnnGensetAsync(reBinModel);
                            if (IsAddSuccess)
                            {
                                result.Code = 1;
                                result.Result = "操作成功！";
                                try
                                {
                                    ////绑定发电记录
                                    //System.Threading.Tasks.Task.Run(() =>
                                    //{
                                    //    AnnounceList Ann = BllHelper.GetANNbyAnnCode(AnnounceCode);
                                    //    if (Ann != null)
                                    //        StatusSyncRoute.BindGen2Ann(Ann);
                                    //});

                                    //向模块写入工单号
                                    //System.Threading.Tasks.Task.Run(() =>
                                    //{
                                    //    if (string.IsNullOrEmpty(registeredDtuId)) return;
                                    //    Generator g = GeneratorList.Frist(registeredDtuId);
                                    //    if (g == null || g.BOnline == false)
                                    //        return;
                                    //    List<CodeValuePair> prs = new List<CodeValuePair>();
                                    //    prs.Add(new CodeValuePair { code = "WORKORDER", value = annouceCode });
                                    //    string dtuCmd = CCommon.StrListToStr((from ii in prs select ii.code + ";" + ii.value).ToList(), ";");
                                    //    string Tmp = TcpCommunication.WritePara(dtuCmd, registeredDtuId, 15);
                                    //});

                                    if (!string.IsNullOrEmpty(registeredDtuId))
                                    {
                                        Generator g = MemoryEntity.gBuffGen[registeredDtuId];// GeneratorList.Frist(registeredDtuId);
                                        if (g != null && g.BOnline != false)
                                        {
                                            List<CodeValuePair> prs = new List<CodeValuePair>();
                                            prs.Add(new CodeValuePair { code = "WORKORDER", value = annouceCode });
                                            string dtuCmd = (from ii in prs select ii.code + ";" + ii.value).ToList().StrListToStr(";");
                                             TcpCommunication.WritePara(dtuCmd, registeredDtuId, 15);
                                        }
                                    }
                                    

                                }
                                catch { }
                                return result;
                            }
                        }
                    }
                }

            }

            return result;
        }

        /// <summary>
        /// 无需发电直接回单方法
        /// </summary>
        /// <param name="annouceCode"></param>
        /// <param name="FinishRemak"></param>
        /// <returns></returns>

        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> UserDirectReceipt(string annouceCode, string FinishRemak)
        {
            ResultModel result = new ResultModel() { Code = 0, Result = "操作失败！" };
            //if (userCode == null || userCode == "")
            //    return result;
            //UserAccountWxModel loginfo = GetLoginInfoWx.Get(userCode);
            var LoginInfo = _workManager.CurrentUser;
            if (LoginInfo == null)
                return result;


            result = await UserOrderBy(annouceCode);
            //默认用户接单.
            if (result.Code == 1) //返回成功，进入下一步操作
            {
                //AnnounceList model = dbContext.Queryable<AnnounceList>().First(x => x.AnnounceCode == annouceCode);
                AnnounceList model =await _infoManager.GetAnnFirstOrDefaultAsync(x => x.AnnounceCode == annouceCode); 
              

                //BaseStation bs = dbContext.Queryable<BaseStation>().First(x => x.BaseStationCode == model.BaseStationCode);
                BaseStation bs =await _infoManager.GetBaseStationFirstAsync(x => x.BaseStationCode == model.BaseStationCode);
            

                int preState = -2;
                int.TryParse(model.AnnounceStatus.ToString() != null && model.AnnounceStatus.ToString() != "" ? model.AnnounceStatus.ToString() : "", out preState);

                string strmysql = "UPDATE dbo.AnnounceList SET	 AnnounceStatus=29,FinishType=1,FinishTime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',FinishRemak='" + FinishRemak + "',PowEveName='' WHERE AnnounceCode='" + annouceCode + "'";
                int Code =await (strmysql).SqlNonQueryAsync();

                if (Code < 0)
                {
                    result.Result = string.Format("工单{0}操作出错！", annouceCode);
                    result.Code = Code;
                    return result;
                }
                //更新工单操作日志
                AnnounceStateXLog annLog = new AnnounceStateXLog();
                annLog.EventType = 8;//回单
                annLog.AnnounceCode = annouceCode;
                //annLog.CreateTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                annLog.CreateTime = DateTime.Now;
                annLog.CreatePerson = LoginInfo.UserCode;
                annLog.CreatePersonName = LoginInfo.UserName;
                annLog.PreState = preState;
                annLog.AuditRemark = FinishRemak;
                annLog.ToState = 29;//已结单
                //annLog.RegisteredDistance = Convert.ToInt32(model.Genset2);
                //annLog.Latitude = Convert.ToDouble(model.Remark);
                //annLog.Longitude = Convert.ToDouble(model.AuditRemark);
                //annLog.FinishType = model.FinishType;
                annLog.FinishType = 1;
                //dbContext.Insertable<AnnounceStateXLog>(annLog).ExecuteCommandAsync();
                await _infoManager.AddAnnounceStateXLog(annLog);
                ////增加运营商审核关联记录
                //List<int> genForls = BllHelper.GetCompanyTypeIntsByKeyStr(model.GenerationFor != null ? model.GenerationFor.ToString() : "");
                //if (genForls != null && genForls.Count > 0)
                //    foreach (int genfor in genForls)
                //    {
                //        AnnounceAudit anna = new AnnounceAudit();
                //        anna.AnnounceCode = annouceCode;
                //        anna.AnnounceStatus = annLog.ToState;
                //        anna.GenerationForCompanyType = genfor;
                //        BllHelper.dbCxt.Add<AnnounceAudit>(anna);
                //    }
                //更新基站状态
                //string basId = bs.BaseStationID.ToString() != null ? bs.BaseStationID.ToString() : "";
                //DataTable dtAnnOfBasID = BllHelper.GetANNbyBasId(basId, new List<int> { 24 });
                //if (dtAnnOfBasID == null || dtAnnOfBasID.Rows.Count <= 0)
                //{
                //    BllHelper.dbOp.SqlUpdata(string.Format("UPDATE dbo.BaseStation SET Status={0} WHERE BaseStationID={1}", 1, basId));
                //    BaseStation bas = BllHelper.basBuff[int.Parse(basId)];
                //    if (bas != null) bas.Status = 1;
                //}


                //计费
                await  GetPowergenerationDataNotFgw(model.AnnounceCode);

                result.Code = 1;
                result.Result = "操作成功";
            }
            else
            {
                result.Code = 0;
                result.Result = "操作失败";
            }
            return result;
        }
        #endregion

        #region 铁塔审核
        /// <summary>
        /// 获取审核工单列表数量（分页）方法
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="times">全部0 一周7 半月15 本月30</param>
        /// <param name="pagesize">每页多少数据，默认50</param>
        /// <param name="topNum">配合sql语句</param>
        /// <param name="menuIndex">页面tab选项 0：全部 1：待审核 2：已审核 3：审核不通过</param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetAnnouceAuditByPages(string userCode, int times = 0, int pagesize = 50, int topNum = 1, int menuIndex = 0, string paraStr = "")
        {
            UserAccount loginfo = _workManager.CurrentUser;
            string notExeDtSql = "";
            string exeingDtSql = "";
            string completeDtSql = "";
            string audiuDtSql = "";
         

            if (loginfo == null)
                return null;
            var whereStr = 0;
            if (paraStr != "" && paraStr != null)
                whereStr = 1;//搜索框有内容
            var whereStr2 = (whereStr == 1) ? (" and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : "";
            if (times == 1)//今日
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ");
            }
            else if (times == -1)//昨日
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))+' 23:59:59') ");
            }
            else if (times == 7)//7天内
            {
                //whereStr2 =  " and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ";
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ");
            }
            else if (times == 30)//本月
            {
                //whereStr2 = " and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') ";
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') ");
            }
            var isAudit = loginfo.PerUrls.Contains("/Gen/AnnounceTeleAudit/Audit");
            string sqlstr = "";
            string notExeDtsqlstr = "";
            //所有
            DataTable notExeDt = new DataTable();
            //待审核
            DataTable exeingDt = new DataTable();
            //审核通过
            DataTable completeDt = new DataTable();
            //审核不通过
            DataTable audiuDt = new DataTable();
            var isOperaterView = false;
            if (isAudit && loginfo.RoleCode != "subadmin")//如果是运营商则只筛选跟他相关的工单
            {
                isOperaterView = true;
                var whereStr1 = "";
                if (loginfo.RoleCode == "ChinaMobileMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 4";
                }
                else if (loginfo.RoleCode == "ChinaUnicomMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 5";
                }
                else if (loginfo.RoleCode == "ChinaTelcomMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 6";
                }
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = " and al.areaCode like '" + loginfo.AreaCode + "%'";
             
                sqlstr = $@" select top {pagesize} al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation,al.GenerationFor,                      
                            al.AcceptPersonName                           
                            al.ExecutionDate,al.AnnounceStatus
                           FROM dbo.AnnounceList AS al {filterCompanyCode} {whereStr1} {whereStr2} and  al.prjcode={loginfo.PrjCode} AND al.AnnounceId > {topNum} ";
                //未审核   

                string orderby = " order by al.AnnounceId ASC";
                //所有 
                //notExeDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus>=29 " + orderby);
                notExeDtSql= (sqlstr + " and AnnounceStatus>=29 " + orderby);
                //待审核   29:已结单  33:已申述  34:运营商否决驳回
                //exeingDt = BllHelper.dbOp.SqlSelect(sqlstr + " and (AnnounceStatus=29 or  AnnounceStatus=33 or AnnounceStatus=34)  " + orderby);
                exeingDtSql= (sqlstr + " and (AnnounceStatus=29 or  AnnounceStatus=33 or AnnounceStatus=34)  " + orderby);
                //审核通过
                //completeDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus=30 " + orderby);
                completeDtSql= (sqlstr + " and AnnounceStatus=30 " + orderby);
                //审核不通过
                //audiuDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus=31 " + orderby);
                audiuDtSql = (sqlstr + " and AnnounceStatus=31 " + orderby);
            }
            else
            {
                isOperaterView = false;
                bool bTurnOrder = loginfo.PerUrls.Contains("/Gen/Announce/UserTurnOrder");
                bool bAllOrder = loginfo.PerUrls.Contains("/api/appservice/GetAnnounceLists");
                string areaFilterStr = iemtm.WeChat.Core.Util.Common.GetAreaFilterStrWx(loginfo.AreaCode, loginfo);
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = commonFilterJustByArea ? areaFilterStr.Replace("(", " where al.").Replace(")", " ") : " where al.AcceptCompanyCode like '" + loginfo.CompanyCode + "%' ";

                sqlstr = "select distinct top " + pagesize + "'" + (bTurnOrder) + "' as bTurnOrder,al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation," +
                    "(select username from UserAccount where usercode=al.AnnouncePerson) as AnnouncePerson,al.AcceptPersonCode,al.AcceptPersonName,al.RegisteredGenset,al.RegisteredAbnormal," +
                    "al.GenManagePersonPhone,al.ExecutionDate as ExecutionDate,AnnounceStatusValue=(select c.DicType from CommType c where c.TabName='AnnounceStatus' and c.DicValue=al.AnnounceStatus)," +
                                  "al.AnnounceStatus from AnnounceList al " + (bAllOrder ? filterCompanyCode : "where (al.AcceptPersonCode='" + loginfo.UserCode + "')") + " and (al.AnnounceStatus{0}) " + "" + whereStr2 + "AND al.AnnounceId > " + topNum + " order by al.AnnounceId ASC";
                string filterIsTieta = commonFilterJustByArea ? "al.AreaCode like '" + loginfo.AreaCode + "%'" : "al.AnnounceCode in (select AnnounceCode from AnnounceCompany where CompanyCode like '" + loginfo.CompanyCode + "%')";
                notExeDtsqlstr = "select distinct top " + pagesize + " al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation," +
             "(select username from UserAccount where usercode=al.AnnouncePerson) as AnnouncePerson,al.AcceptPersonCode,al.AcceptPersonName,al.RegisteredGenset,al.RegisteredAbnormal," +
             "al.GenManagePersonPhone,al.ExecutionDate as ExecutionDate,AnnounceStatusValue=(select c.DicType from CommType c where c.TabName='AnnounceStatus' and c.DicValue=al.AnnounceStatus),al.AnnounceStatus from AnnounceList al where " + filterIsTieta + " and (al.AnnounceStatus={0} " + whereStr2 + "AND al.AnnounceId > " + topNum + " order by al.AnnounceId ASC";

                sqlstr = $@" select top {pagesize} al.AnnounceId,al.AnnounceCode,al.JobNumber,al.AreaCode,al.BaseStationID,al.BaseStation,al.GenerationFor, 
                          al.AcceptPersonName,
                           al.ExecutionDate,al.AnnounceStatus
                FROM dbo.AnnounceList AS al {filterCompanyCode} {whereStr2} and  al.prjcode={loginfo.PrjCode}    and {areaFilterStr} AND al.AnnounceId > {topNum} ";

                string orderby = " order by al.AnnounceId ASC";
                //所有 
                //notExeDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus>=29 " + orderby);
                notExeDtSql = (sqlstr + " and AnnounceStatus>=29 " + orderby);
                //待审核   29:已结单  33:已申述  34:运营商否决驳回
                //exeingDt = BllHelper.dbOp.SqlSelect(sqlstr + " and (AnnounceStatus=29 or  AnnounceStatus=33 or AnnounceStatus=34)  " + orderby);
                exeingDtSql= (sqlstr + " and (AnnounceStatus=29 or  AnnounceStatus=33 or AnnounceStatus=34)  " + orderby);
                //审核通过
                //completeDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus=30 " + orderby);
                completeDtSql= (sqlstr + " and AnnounceStatus=30 " + orderby);
                //审核不通过
                //audiuDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus=31 " + orderby);
                audiuDtSql= (sqlstr + " and AnnounceStatus=31 " + orderby);
            }


            switch (menuIndex)
            {
                case 0://待接单
                    if (!string.IsNullOrEmpty(notExeDtSql))
                    {
                        notExeDt = await notExeDtSql.SqlQueryAsync();
                    }
                    return new
                    {
                        isAudit = isAudit,
                        isOperaterView = isOperaterView,
                        noExtTotal = notExeDt.Rows.Count,
                        noEx = notExeDt.ToDynamicList()
                    };
                case 1://执行中
                    if (!string.IsNullOrEmpty(exeingDtSql))
                    {
                        exeingDt = await exeingDtSql.SqlQueryAsync();
                    }
                    return new
                    {
                        isAudit = isAudit,
                        isOperaterView = isOperaterView,
                        exingTotal = exeingDt.Rows.Count,
                        exeing = exeingDt.ToDynamicList()
                    };
                case 2://已结单
                    if (!string.IsNullOrEmpty(completeDtSql))
                    {
                        completeDt = await completeDtSql.SqlQueryAsync();
                    }
                    return new
                    {
                        isAudit = isAudit,
                        isOperaterView = isOperaterView,
                        completelyTotal = completeDt.Rows.Count,
                        completely = completeDt.ToDynamicList()
                    };
                case 3://已审核
                    if (!string.IsNullOrEmpty(audiuDtSql))
                    {
                        audiuDt = await audiuDtSql.SqlQueryAsync();
                    }
                    return new
                    {
                        isAudit = isAudit,
                        isOperaterView = isOperaterView,
                        audiuTotal = audiuDt.Rows.Count,
                        audiu = audiuDt.ToDynamicList()
                    };
                default://返回空数据
                    return new
                    {
                        isAudit = isAudit,
                        isOperaterView = isOperaterView,
                        audiuTotal = 0,
                        audiu = "[]"
                    };
            }

        }

        /// <summary>
        /// 统计审核工单数量方法
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetAnnouceAuditCounts(string userCode, int times = 0, string paraStr = "")
        {
            string exeingDtSql = "";
            string completeDtSql = "";
            string audiuDtSql = "";
            string notExeDtSql = "";
           
            var loginfo = _workManager.CurrentUser;
            if (loginfo == null)
                return null;
            var whereStr = 0;
            if (paraStr != "" && paraStr != null)
                whereStr = 1;//搜索框有内容
            var whereStr2 = (whereStr == 1) ? (" and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : "";
            if (times == 1)//今天
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ");
            }
            else if (times == -1)//昨日
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))+' 23:59:59') ");
            }
            else if (times == 7)//7天内
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ");
                //whereStr2 = " and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')";
            }
            else if (times == 30)//本月
            {
                whereStr2 = (whereStr == 1) ? (" and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')") : (" and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') ");
                //whereStr2 = " and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')";
            }
            var isAudit = loginfo.PerUrls.Contains("/Gen/AnnounceTeleAudit/Audit");
            string sqlstr = "";
            string notExeDtsqlstr = "";
            //所有
            DataTable notExeDt = new DataTable();
            //待审核
            DataTable exeingDt = new DataTable();
            //审核通过
            DataTable completeDt = new DataTable();
            //审核不通过
            DataTable audiuDt = new DataTable();


            var isOperaterView = false;
            if (isAudit && loginfo.RoleCode != "subadmin")//如果是运营商则只筛选跟他相关的工单
            {
                isOperaterView = true;
                var whereStr1 = "";
                if (loginfo.RoleCode == "ChinaMobileMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 4";
                }
                else if (loginfo.RoleCode == "ChinaUnicomMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 5";
                }
                else if (loginfo.RoleCode == "ChinaTelcomMonitor")
                {
                    whereStr1 = " and aa.GenerationForCompanyType = 6";
                }
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = " and al.areaCode like '" + loginfo.AreaCode + "%'";
            
                sqlstr = $"SELECT COUNT(*) as count FROM dbo.AnnounceList AS al {filterCompanyCode} {whereStr1} {whereStr2} and  al.prjcode={loginfo.PrjCode}";
                //所有 
                //notExeDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus>=29 ");
                notExeDtSql = (sqlstr + " and AnnounceStatus>=29 ");
                //待审核   29:已结单  33:已申述  34:运营商否决驳回
                //exeingDt = BllHelper.dbOp.SqlSelect(sqlstr + " and (AnnounceStatus=29 or  AnnounceStatus=33 or AnnounceStatus=34)  ");
                exeingDtSql= (sqlstr + " and (AnnounceStatus=29 or  AnnounceStatus=33 or AnnounceStatus=34)  ");
                //审核通过
                //completeDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus=30 ");
                completeDtSql= (sqlstr + " and AnnounceStatus=30 ");
                //审核不通过
                //audiuDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus=31 ");
                audiuDtSql = (sqlstr + " and AnnounceStatus=31 ");
            }
            else
            {
                isOperaterView = false;
                bool bTurnOrder = loginfo.PerUrls.Contains("/Gen/Announce/UserTurnOrder");
                bool bAllOrder = loginfo.PerUrls.Contains("/api/appservice/GetAnnounceLists");
                string areaFilterStr = iemtm.WeChat.Core.Util.Common.GetAreaFilterStrWx(loginfo.AreaCode, loginfo);
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = commonFilterJustByArea ? areaFilterStr.Replace("(", " where al.").Replace(")", " ") : " where al.AcceptCompanyCode like '" + loginfo.CompanyCode + "%' ";

                sqlstr = $"SELECT COUNT(*) as count FROM dbo.AnnounceList AS al {filterCompanyCode} {whereStr2} and  al.prjcode={loginfo.PrjCode}    and {areaFilterStr} ";
                //所有 
                //notExeDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus>=29 ");
                notExeDtSql = (sqlstr + " and AnnounceStatus>=29 ");

                //待审核   29:已结单  33:已申述  34:运营商否决驳回
                //exeingDt = BllHelper.dbOp.SqlSelect(sqlstr + " and (AnnounceStatus=29 or  AnnounceStatus=33 or AnnounceStatus=34)  ");
                exeingDtSql = (sqlstr + " and (AnnounceStatus=29 or  AnnounceStatus=33 or AnnounceStatus=34)  ");

                //审核通过
                //completeDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus=30 ");
                completeDtSql = (sqlstr + " and AnnounceStatus=30 ");

                //审核不通过
                //audiuDt = BllHelper.dbOp.SqlSelect(sqlstr + " and AnnounceStatus=31 ");
                audiuDtSql =(sqlstr + " and AnnounceStatus=31 ");

            }

            
            notExeDt =await notExeDtSql.SqlQueryAsync();
            exeingDt = await exeingDtSql.SqlQueryAsync();
            completeDt = await completeDtSql.SqlQueryAsync();
            audiuDt = await audiuDtSql.SqlQueryAsync();

            

            return new
            {
                isAudit = isAudit,
                isOperaterView = isOperaterView,
                noExtTotal = notExeDt.Rows[0]["count"],
                exingTotal = exeingDt.Rows[0]["count"],
                completelyTotal = completeDt.Rows[0]["count"],
                audiuTotal = audiuDt.Rows[0]["count"],

            };
        }
        /// <summary>
        /// 审核工单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> AnnAudit(int AnnounceStatus, string AuditRemark, string GenImg1)
        {
            var loginfo = _workManager.CurrentUser;
            AnnounceList model = new AnnounceList();
            model.GenImg1 = GenImg1;
            model.AnnounceStatus = AnnounceStatus;
            model.AuditRemark = AuditRemark;
            List<string> annidList =model.GenImg1.StringSplitTirm(",").ToList();
            //if (model.FinishType == 2 && model.CreateDate > model.FinishTime)
            //    return new { code = -1, result = "发电开始时间不能大于发电结束时间!" };
            if (annidList == null || annidList.Count <= 0)
                return new { code = -1, result = "操作失败!" };
            DataTable annList =await GetANNbyAnnIds(annidList);
            if (annList == null || annList.Rows.Count <= 0)
                return new { code = -1, result = "操作失败!" };

            DataTable annAuditList =await GetANNAuditbyAnnIds(annidList);
            if (annAuditList.Rows.Count > 0)
                return new { code = -1, result = "操作失败!存在未消除的运营商工单" };
            int code = -1;
            string result = string.Format("[{0}] 提交成功！", (model.AnnounceStatus == 30 ? "审核通过" : "审核不通过"));
            foreach (DataRow dr in annList.Rows)
            {
                string annid = dr["AnnounceId"].ToString();
                string annCode = dr["AnnounceCode"].ToString();
                //string jobNo = dr["JobNumber"] == null ? "" : dr["JobNumber"].ToString();
                //jobNo = jobNo == "" ? annCode : jobNo;
                int preState = -2;
                int.TryParse(dr["AnnounceStatus"] != null && dr["AnnounceStatus"].ToString() != "" ? dr["AnnounceStatus"].ToString() : "", out preState);
                var userCode = dr["AcceptPersonCode"] == null ? "" : dr["AcceptPersonCode"].ToString();
                UserAccount acceptPerson =await _userManager.CheckUserAsync(userCode);// BllHelper.GetUser(dr["AcceptPersonCode"] == null ? "" : dr["AcceptPersonCode"].ToString());

                //model.AnnounceStatus = 30，31;//更改工单状态为已审核或审核不通过：0:未执行、1:执行中、2:已完成、3:审核通过、4：审核未通过
                //string[] strmysql = new string[] { "update AnnounceList set AnnounceStatus=" + model.AnnounceStatus.ToString() + ", AuditRemark='" + model.AuditRemark + "'  where AnnounceId=" + annid + "" };
                string strmysql = "update AnnounceList set AnnounceStatus=" + model.AnnounceStatus.ToString() + ", AuditRemark='" + model.AuditRemark + "', AuditCode='" + loginfo.UserCode + "', AuditName='" + loginfo.UserName + "', AduitTime='" + DateTime.Now + "' where AnnounceId=" + annid + "" ;//添加审核人
                code = await strmysql.SqlNonQueryAsync(); 
                if (code <= 0)
                {
                    result = string.Format("工单{0}操作出错!", annid);
                    break;
                }
                //更新手工登记记录的发电起止时间
                if (model.FinishType == 2)
                {
                    string sql = string.Format("UPDATE dbo.GenRecord SET GenStart='{0}',GenStop='{1}' ,RunningPeriod='{3}' WHERE GenRecordId IN (SELECT GenRecordId FROM dbo.AnnounceGen WHERE AnnounceId={2})",
                        model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss"), model.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), annid,
                        (model.FinishTime.Value - model.CreateDate.Value).TotalHours);
                    await (sql).SqlNonQueryAsync();
                }

                //增加运营商审核关联记录
                if (model.AnnounceStatus == 30)
                {
                    List<int> genForls = GetCompanyTypeIntsByKeyStr(dr["GenerationFor"] != DBNull.Value ? dr["GenerationFor"].ToString() : "");
                    if (genForls != null && genForls.Count > 0)
                        foreach (int genfor in genForls)
                        {
                            AnnounceAudit anna = new AnnounceAudit();
                            anna.AnnounceCode = annCode;
                            //anna.AnnounceStatus = model.AnnounceStatus;
                            anna.AnnounceStatus = 29;//默认已结单
                            anna.GenerationForCompanyType = genfor;
                            // BllHelper.dbCxt.Add<AnnounceAudit>(anna);
                            await _infoManager.AddAnnounceAuditAsync(anna);
                            
                        }
                }


                //更新工单操作日志
                AnnounceStateXLog annLog = new AnnounceStateXLog();
                annLog.EventType = 9;//审核
                annLog.AnnounceCode = annCode;
                annLog.CreateTime = DateTime.Now;
                annLog.CreatePerson = loginfo.UserCode;
                annLog.CreatePersonName = loginfo.UserName;
                annLog.PreState = preState;
                annLog.ToState = model.AnnounceStatus;//审核后状态
                annLog.AuditRemark = model.AuditRemark;//备注
                //BllHelper.dbCxt.Add<AnnounceStateXLog>(annLog);
                await _infoManager.AddAnnounceStateXLog(annLog);

                //============推送===================
          
                #region 微信推送审核失败工单
                if (model.AnnounceStatus == 31)
                {
                    string AcceptPersonCodeS = dr["AcceptPersonCode"].ToString();
                    string AnnounceCodeS = dr["AnnounceCode"].ToString();
                    string JobNumberS = dr["JobNumber"].ToString();
                    if (!string.IsNullOrEmpty(AcceptPersonCodeS) && !string.IsNullOrEmpty(AnnounceCodeS) && !string.IsNullOrEmpty(JobNumberS))
                    {
                        
                       await WeiXinPush.SendUnAnnounce(AcceptPersonCodeS, AnnounceCodeS, JobNumberS, model.AuditRemark);
                       
                    }
                }
                #endregion
            }
            return new { code = code, result = result };

        }

        #endregion

        #region 运营商审核
        /// <summary>
        /// 获取运营商审核工单（分页）
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="times">全部0 一周7 半月15 本月30</param>
        /// <param name="pagesize">每页多少数据，默认50</param>
        /// <param name="topNum">配合sql语句</param>
        /// <param name="menuIndex">页面tab选项 0：全部 1：待审核 2：已审核 3：审核不通过</param>
        /// <param name="paraStr"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetAnnounceListsByPage_AnnounceTeleAudit(string userCode, int times = 0, int pagesize = 50, int topNum = 1, int menuIndex = 0, string paraStr = "")
        {
            var loginfo = _workManager.CurrentUser;
            if (loginfo == null)
                return null;
            var whereStr2 = "";
            //时间
            if (times == 1)//今天
            {
                whereStr2 = " and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ";
            }
            else if (times == -1)//昨日
            {
                whereStr2 = " and al.ExecutionDate>=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))+' 23:59:59') ";

            }
            else if (times == 7)//7天内
            {
                whereStr2 = " and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ";

            }
            else if (times == 30)//本月
            {
                whereStr2 = " and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') ";
            }
            if (!string.IsNullOrEmpty(paraStr))
            {
                whereStr2 += $"and (al.BaseStation like '%{paraStr}%' or al.JobNumber like '%{paraStr}%' or al.AnnounceCode like '%{paraStr}%')";
            }
            var isAudit = loginfo.PerUrls.Contains("/Gen/AnnounceTeleAudit/Audit");
            
      
            var isOperaterView = false;
            string RoleCode_Temp = loginfo.RoleCode;
            if (isAudit && (RoleCode_Temp == "subadmin" || RoleCode_Temp == "ChinaMobileMonitor" || RoleCode_Temp == "ChinaUnicomMonitor" || RoleCode_Temp == "ChinaTelcomMonitor"))//如果是运营商则只筛选跟他相关的工单
            {
                isOperaterView = true;
                var whereStr1 = "";
                //运营商
                if (loginfo.RoleCode == "ChinaMobileMonitor")
                {
                    whereStr1 = " and a.GenerationForCompanyType = 4";
                }
                else if (loginfo.RoleCode == "ChinaUnicomMonitor")
                {
                    whereStr1 = "and  a.GenerationForCompanyType = 5";
                }
                else if (loginfo.RoleCode == "ChinaTelcomMonitor")
                {
                    whereStr1 = " and a.GenerationForCompanyType = 6";
                }
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                //区域
                string filterCompanyCode = " and al.areaCode like '" + loginfo.AreaCode + "%'";

                string sqlstrS = $"SELECT top {pagesize} a.Id, al.BaseStation,al.AcceptPersonName,a.AnnounceStatus,al.AnnounceCode,al.ExecutionDate,al.JobNumber,a.GenerationForCompanyType FROM AnnounceAudit a LEFT JOIN AnnounceList al ON a.AnnounceCode = al.AnnounceCode where al.prjcode={loginfo.PrjCode }{whereStr1} {filterCompanyCode} {whereStr2} AND a.Id > {topNum}";

                string sql_total = $"{sqlstrS} and a.AnnounceStatus>=29 ORDER BY a.Id ASC ";
                string sql_29 = $"{sqlstrS} and a.AnnounceStatus=29 ORDER BY a.Id ASC ";
                string sql_30 = $"{sqlstrS} and a.AnnounceStatus=30 ORDER BY a.Id ASC";
                string sql_31 = $"{sqlstrS} and a.AnnounceStatus=31 ORDER BY a.Id ASC";

                DataTable AnnounceStatus_total =new DataTable();
                DataTable AnnounceStatus_29 = new DataTable();
                DataTable AnnounceStatus_30 = new DataTable();
                DataTable AnnounceStatus_31 = new DataTable();
                //audiuDt = BllHelper.dbOp.SqlSelect(string.Format(sqlstr, "=30)"));
                //var noEx = DBCommon.ToDynamic(AnnounceStatus_29);

                switch (menuIndex)
                {
                    case 0://全部
                        if (!string.IsNullOrEmpty(sql_total))
                        {
                            AnnounceStatus_total =await sql_total.SqlQueryAsync();
                        }
                        return new
                        {

                            isOperaterView = isOperaterView,
                            noExtTotal = AnnounceStatus_total.Rows.Count,
                            noEx = AnnounceStatus_total.ToDynamicList()
                        };
                    case 1://待审核
                        if (!string.IsNullOrEmpty(sql_29))
                        {
                            AnnounceStatus_29 = await sql_29.SqlQueryAsync();
                        }
                        return new
                        {
                            isOperaterView = isOperaterView,
                            exingTotal = AnnounceStatus_29.Rows.Count,
                            exeing =AnnounceStatus_29.ToDynamicList()
                        };
                    case 2://审核通过
                        if (!string.IsNullOrEmpty(sql_30))
                        {
                            AnnounceStatus_30 = await sql_30.SqlQueryAsync();
                        }
                        return new
                        {
                            isOperaterView = isOperaterView,
                            completelyTotal = AnnounceStatus_30.Rows.Count,
                            completely = AnnounceStatus_30.ToDynamicList()
                        };
                    case 3://审核不通过
                        if (!string.IsNullOrEmpty(sql_31))
                        {
                            AnnounceStatus_31 = await sql_31.SqlQueryAsync();
                        }
                        return new
                        {
                            isOperaterView = isOperaterView,
                            audiuTotal = AnnounceStatus_31.Rows.Count,
                            audiu = AnnounceStatus_31.ToDynamicList()
                        };
                }
            }
            return new
            {
                isAudit = isAudit,
                isOperaterView = isOperaterView,
                audiuTotal = 0,
                audiu = new List<string>(),
                noEx = new List<string>(),
                exeing = new List<string>(),
                completely = new List<string>(),
            };



        }

        /// <summary>
        /// 获取运营商审核工单数量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async  Task<dynamic> GetAlarmCounts_AnnounceTeleAudit(string userCode, int times = 0, string paraStr = "")
        {
            var loginfo = _workManager.CurrentUser;
            if (loginfo == null)
                return null;
            var whereStr2 = "";
            //时间
            if (times == 1)//今天
            {
                whereStr2 = " and al.ExecutionDate>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ";
            }
            else if (times == -1)//昨日
            {
                whereStr2 = " and al.ExecutionDate>=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select dateadd(day,-1,(select CONVERT(varchar(30),GETDATE(),23)))+' 23:59:59') ";

            }
            else if (times == 7)//7天内
            {
                whereStr2 = " and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') ";

            }
            else if (times == 30)//本月
            {
                whereStr2 = " and al.ExecutionDate>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') ";
            }
            if (!string.IsNullOrEmpty(paraStr))
            {
                whereStr2 += $"and (al.BaseStation like '%{paraStr}%' or al.JobNumber like '%{paraStr}%' or al.AnnounceCode like '%{paraStr}%')";
            }

            var isOperaterView = false;
            string RoleCode_Temp = loginfo.RoleCode;
            var isAudit = loginfo.PerUrls.Contains("/Gen/AnnounceTeleAudit/Audit");
            if (isAudit&&(RoleCode_Temp == "subadmin" || RoleCode_Temp == "ChinaMobileMonitor" || RoleCode_Temp == "ChinaUnicomMonitor" || RoleCode_Temp == "ChinaTelcomMonitor"))//如果是运营商则只筛选跟他相关的工单
            {
                isOperaterView = true;
                var whereStr1 = "";
                //运营商
                if (loginfo.RoleCode == "ChinaMobileMonitor")
                {
                    whereStr1 = "and  a.GenerationForCompanyType = 4";
                }
                else if (loginfo.RoleCode == "ChinaUnicomMonitor")
                {
                    whereStr1 = " and a.GenerationForCompanyType = 5";
                }
                else if (loginfo.RoleCode == "ChinaTelcomMonitor")
                {
                    whereStr1 = "and  a.GenerationForCompanyType = 6";
                }
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");

                //区域
                string filterCompanyCode = " and al.areaCode like '" + loginfo.AreaCode + "%'";
                string sqlstr = $"SELECT COUNT(*) AS count FROM  AnnounceAudit a LEFT JOIN AnnounceList al  ON a.AnnounceCode=al.AnnounceCode  where  al.prjcode= { loginfo.PrjCode} {whereStr1} {filterCompanyCode} {whereStr2 } ";
                string sql_total = $"{sqlstr} and a.AnnounceStatus>=29";
                string sql_29 = $"{sqlstr} and a.AnnounceStatus=29";
                string sql_30 = $"{sqlstr} and a.AnnounceStatus=30";
                string sql_31 = $"{sqlstr} and a.AnnounceStatus=31";

                DataTable AnnounceStatus_total =await (sql_total).SqlQueryAsync();
                DataTable AnnounceStatus_29 = await (sql_29).SqlQueryAsync();
                DataTable AnnounceStatus_30 = await (sql_30).SqlQueryAsync();
                DataTable AnnounceStatus_31 = await (sql_31).SqlQueryAsync();

                return new
                {

                    isOperaterView = isOperaterView,

                    noExtTotal = AnnounceStatus_total.Rows[0]["count"],
                    exingTotal = AnnounceStatus_29.Rows[0]["count"],
                    completelyTotal = AnnounceStatus_30.Rows[0]["count"],
                    audiuTotal = AnnounceStatus_31.Rows[0]["count"]
                };

            }
            return new
            {

                isOperaterView = isOperaterView,
                noExtTotal = 0,
                exingTotal = 0,
                completelyTotal = 0,
                audiuTotal = 0
            };
        }

        /// <summary>
        /// 运营商审核
        /// </summary>
        /// <param name="prjCode"></param>
        /// <param name="openId"></param>
        /// <param name="GenImg1"></param>
        /// <param name="AnnounceStatus"></param>
        /// <param name="AuditRemark"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> Audit_AnnounceTeleAudit(string prjCode, string openId, string GenImg1, int AnnounceStatus, string AuditRemark)
        {
            var loginfo = _workManager.CurrentUser;
            AnnounceList model = new AnnounceList();
            model.GenImg1 = GenImg1;
            model.AnnounceStatus = AnnounceStatus;
            model.AuditRemark = AuditRemark;
            List<string> annaidList = model.GenImg1.StringSplitTirm(",").ToList();
            //if (model.FinishType == 2 && model.CreateDate > model.FinishTime)
            //    return new { code = -1, result = "发电开始时间不能大于发电结束时间!" };
            if (annaidList == null || annaidList.Count <= 0)
                return new { code = -1, result = "操作失败!" };

            string result = string.Format("[{0}] 提交成功！",model.AnnounceStatus == 30 ? "审核通过" : "审核不通过");

            try
            {
                foreach (string annaid in annaidList)
                {

                    int AnnId = int.Parse(annaid);
                    AnnounceAudit anna = await _infoManager.GetAnnounceAuditFirstAsync(e => e.Id == AnnId);
                    anna.AuditRemark = model.AuditRemark;
                    anna.AnnounceStatus = model.AnnounceStatus;
                    //添加审核人与Id
                    anna.AuditCode = loginfo.UserCode;
                    anna.AuditName = loginfo.UserName;
                    anna.AduitTime = DateTime.Now;
                    _infoManager.UpdateAnnounceAuditInclude(anna, new[] {
                        nameof(anna.AuditRemark),
                        nameof(anna.AnnounceStatus),
                        nameof(anna.AuditCode),
                        nameof(anna.AuditName),
                        nameof(anna.AduitTime),
                    });
                    // BllHelper.dbCxt.Update<AnnounceAudit>(anna);
                }
                return new { code = 1, result = result };
            }
            catch (Exception e)
            {
                return new { code = -1, result = "审核出错!" +e.Message}; 
            }
        }

            #endregion

       #region  -工单签到-回单 用到的方法





            /// <summary>
            /// 用户接单
            /// </summary>
            /// <param name="announceCode"></param>
            /// <returns></returns>
            private async Task<ResultModel> UserOrderBy(string announceCode)
        {
            ResultModel result = new ResultModel() { Code = 0 };
            var LoginInfo = _workManager.CurrentUser;
            //var announceList = dbContext.Queryable<AnnounceList>().First(u => u.AnnounceCode == announceCode);
            var announceList =await _infoManager.GetAnnFirstOrDefaultAsync(u => u.AnnounceCode == announceCode); 
            if (announceList.AnnounceStatus > 20 && announceList.AnnounceStatus != 27)//表示该订单已接单
            {
                result.Code = -1;//订单已接单
                if (announceList.AcceptPersonCode == LoginInfo.UserCode)
                {
                    result.Code = -2;//表示该订单已经被该用户已接单，无需重新已接单
                }
            }
            else if (announceList.AnnounceStatus == 20 || announceList.AnnounceStatus == 27)
            {
                int oldStatus = announceList.AnnounceStatus.Value;
                announceList.AnnounceStatus = oldStatus == 27 ? 28 : 21;
                announceList.AcceptPersonCode = LoginInfo.UserCode;
                announceList.AcceptPersonName = LoginInfo.UserName;
                announceList.AcceptCompanyCode = LoginInfo.CompanyCode;
                announceList.AcceptCompanyName = LoginInfo.CompanyName;
                int count = 0;
                bool UpdataSuccess = false;
                if (oldStatus == 20)//只有正常接单才记录接单时间
                {
                    announceList.AcceptTime = DateTime.Now;

                    string[] upcolumn = new[] {
                    nameof(announceList.AnnounceStatus)
                        , nameof(announceList.AcceptPersonCode)
                        , nameof(announceList.AcceptPersonName)
                        , nameof(announceList.AcceptCompanyCode)
                        , nameof(announceList.AcceptCompanyName)
                        , nameof(announceList.AcceptTime)

                    };
                    
                     UpdataSuccess= _infoManager.UpdateAnnUpdateInclude(announceList, upcolumn);
                    
                }
                else
                {
                    
                     string[] upcolumn = new[] {
                    nameof(announceList.AnnounceStatus)
                        , nameof(announceList.AcceptPersonCode)
                        , nameof(announceList.AcceptPersonName)
                        , nameof(announceList.AcceptCompanyCode)
                        , nameof(announceList.AcceptCompanyName)
                      

                    };
                    UpdataSuccess=_infoManager.UpdateAnnUpdateInclude(announceList, upcolumn);
                }
                if (UpdataSuccess)
                {
                    count = 1;
                    result.Code = announceList.AcceptPersonCode == LoginInfo.UserCode ? 1 : -1;//判断当前工单的发电人是否为当前登录用户，如果是则表示接单成功.
                    var eventype = oldStatus == 20 ? 2 : 7;//2接单，7告警接单
                    AnnounceStateXLog annlLog = new AnnounceStateXLog() { EventType = eventype, CreatePerson = LoginInfo.UserCode, CreatePersonName = LoginInfo.UserName, CreateTime = DateTime.Now, PreState = oldStatus, ToState = announceList.AnnounceStatus, AnnounceCode = announceCode };
                   // dbContext.Insertable(annlLog).ExecuteCommand();
                  await  _infoManager.AddAnnounceStateXLog(annlLog);
                }
                else
                {
                    result.Code = 0;//接单失败
                }
            }
            return result;
        }
     
        /// <summary>
        /// 微信公众号工单动态绑定油机与采集器造成Generator表的修改接口方法
        /// </summary>
        /// <param name="GensetNum"></param>
        /// <param name="Dtuid"></param>
        /// <returns></returns>

        private async Task<dynamic> EditGenDtuid(string GensetNum, string Dtuid)
        {
            ResultModel result = new ResultModel() { Code = 0, Result = "会话过期" };
            try
            {
                //根据GensetNum从数据库表拿到当前数据
                //Generator Gmodel =MemoryEntity.gBuffGen.All.Values.FirstOrDefault(x => x.GensetNum == GensetNum);            
                //if (Gmodel == null)
                //    return new ResultModel() { Code = 0, Result = "不存在此油机." };
                //从缓存拿出数据
                //项目筛选
                Generator gbuff = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(x => x.GensetNum == GensetNum);
                if (gbuff == null)
                    return new ResultModel() { Code = 0, Result = "不存在此油机." };

                //油机与采集器为正常组合
                if (gbuff.DTUID == Dtuid)
                    return new ResultModel() { Code = 3, Result = "油机采集器组合正常" };
                if (gbuff == null)
                    return new ResultModel() { Code = 2, Result = "油机编号已被使用" };
                //固定采集器，不可更改
                if (gbuff.IsFixedSetup == true)
                    return new ResultModel() { Code = 2, Result = "此油机为固定安装方式，若要修改请联系管理员" };
                List<Generator> gListTmp = MemoryEntity.gBuffGen.All.Values.Where(x => x.GeneratorId != gbuff.GeneratorId && x.DTUID != null && x.DTUID == Dtuid.Trim()).ToList();
                if (gListTmp != null && gListTmp.Count > 0)//采集器被其他油机使用
                {
                    if (gListTmp[0].IsFixedSetup == true)//为固定采集器，不可更改
                        return new ResultModel() { Code = 2, Result = "此采集器与其他油机为固定安装方式，若要修改请联系管理员" };
                    //不为固定采集器，先将DTUID清空
                    //Generator oldGbuff = MemoryEntity.gBuffGen.All.Values.FirstOrDefault() GeneratorList.Frist(gListTmp[0].GeneratorId);
                    //oldGbuff.DTUID = "";
                    gListTmp[0].DTUID = "";
                    //更新数据库
                    // dbContext.Updateable<Generator>(oldGbuff).UpdateColumns(it => new { it.DTUID }).ExecuteCommand();
                    await string.Format("update Generator set DTUID='{0}' where GeneratorId={1}", "", gListTmp[0].GeneratorId).SqlNonQueryAsync();
                }
                //更新此油机绑定的采集器DTUID
                gbuff.DTUID = Dtuid;

                await string.Format("update Generator set DTUID='{0}' where GeneratorId={1}", gbuff.DTUID, gbuff.GeneratorId).SqlNonQueryAsync();
                result.Code = 1;
                result.Result = "更新采集器成功";
            }
            catch (Exception e)
            {
                result.Code = 0;
                result.Result = "会话失败，请联系管理员";
            }
            return result;
        }


        /// <summary>
        /// 判断是否结束之前工单
        /// </summary>
        /// <param name="dtuid"></param>
        /// <returns></returns>
        private async Task<dynamic> CheckGenIsBindAnnounce(string dtuid)
        {
            ResultModel result = new ResultModel() { Code = 1, Result = "OK" };
            try
            {
                //优先判断工单表
                string AnnSql = $"SELECT AnnounceCode,JobNumber,AcceptPersonName,AcceptPersonCode FROM dbo.AnnounceList WHERE AnnounceStatus >=22 AND AnnounceStatus<=28 AND	 RegisteredDtuId='{dtuid}'";
                DataTable AnnDT =await (AnnSql).SqlQueryAsync();
                string AnnounceCode = "";
                string JobNumber = "";
                string AcceptPersonName = "";
                string AcceptPersonCode = "";
                if (AnnDT.Rows.Count > 0)
                {
                    AnnounceCode = AnnDT.Rows[0]["AnnounceCode"].ToString();
                    JobNumber = AnnDT.Rows[0]["JobNumber"].ToString();
                    AcceptPersonName = AnnDT.Rows[0]["AcceptPersonName"].ToString();
                    AcceptPersonCode = AnnDT.Rows[0]["AcceptPersonCode"].ToString();
                    result.Code = 0;
                    result.Result = $"该采集器存在未结束的工单:{JobNumber},接单人:{AcceptPersonName},手机号:{AcceptPersonCode},请结束后再进行操作！";
                    return result;
                }
                string ReBinAnnSql = $"SELECT a.AnnounceCode,a.JobNumber,a.AcceptPersonName,a.AcceptPersonCode FROM dbo.ReBinAnnGenset r LEFT JOIN dbo.AnnounceList a ON r.AnnounceCode=a.AnnounceCode WHERE a.AnnounceStatus>=22 AND a.AnnounceStatus <=28 AND r.RegisteredDtuId='{dtuid}'";
                DataTable ReBinDT =await (ReBinAnnSql).SqlQueryAsync();
                if (ReBinDT.Rows.Count > 0)
                {
                    AnnounceCode = ReBinDT.Rows[0]["AnnounceCode"].ToString();
                    JobNumber = ReBinDT.Rows[0]["JobNumber"].ToString();
                    AcceptPersonName = ReBinDT.Rows[0]["AcceptPersonName"].ToString();
                    AcceptPersonCode = ReBinDT.Rows[0]["AcceptPersonCode"].ToString();
                    result.Code = 0;
                    result.Result = $"该采集器存在未结束的工单:{JobNumber},接单人:{AcceptPersonName},手机号:{AcceptPersonCode},请结束后再进行操作！";
                    return result;
                }
                string ChangeAnnSql = $"SELECT a.AnnounceCode,a.JobNumber,a.AcceptPersonName,a.AcceptPersonCode FROM dbo.ChangeAnnGenset c LEFT JOIN dbo.AnnounceList a ON c.AnnounceCode=a.AnnounceCode WHERE a.AnnounceStatus>=22 AND a.AnnounceStatus <=28 AND c.RegisteredDtuId='{dtuid}'";
                DataTable ChangeAnnDT =await (ChangeAnnSql).SqlQueryAsync();
                if (ChangeAnnDT.Rows.Count > 0)
                {
                    AnnounceCode = ChangeAnnDT.Rows[0]["AnnounceCode"].ToString();
                    JobNumber = ChangeAnnDT.Rows[0]["JobNumber"].ToString();
                    AcceptPersonName = ChangeAnnDT.Rows[0]["AcceptPersonName"].ToString();
                    AcceptPersonCode = ChangeAnnDT.Rows[0]["AcceptPersonCode"].ToString();
                    result.Code = 0;
                    result.Result = $"该采集器存在未结束的工单:{JobNumber},接单人:{AcceptPersonName},手机号:{AcceptPersonCode},请结束后再进行操作！";
                    return result;
                }
            }
            catch (Exception e)
            {
                result.Code = 0;
                result.Result = "会话失败！";
                return result;
            }
            return result;
        }


        /// <summary>
        /// 用户签到
        /// </summary>
        /// <param name="registeredGenset"></param>
        /// <param name="announceCode"></param>
        /// <param name="registeredAbnormal"></param>
        /// <param name="longitude"></param>
        /// <param name="latitude"></param>
        /// <param name="registeredDistance"></param>
        /// <param name="generationFor"></param>
        /// <param name="registeredDtuId"></param>
        /// <returns></returns>
        private async  Task<ResultModel> UserSignIn(string registeredGenset, string announceCode, bool registeredAbnormal, double longitude, double latitude, int registeredDistance, string generationFor, string registeredDtuId = null, string userCode = null)
        {
            ResultModel result = new ResultModel() { Code = 0 };

            var announceList =await _infoManager.GetAnnFirstOrDefaultAsync(u => u.AnnounceCode == announceCode);
          
            if (announceList.AnnounceStatus > 22) //表示该订单已签到
            {
                result.Code = -1;//订单已签到
            }
            else if (announceList.AnnounceStatus == 21 && announceList.RegisteredGenset == null)
            {
                //查询油机状态
                var dtuid = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(c => c.GeneratorCode == registeredGenset || c.DTUID == registeredGenset);
          
                if (dtuid != null && dtuid.bRunning==true)
                {
                    announceList.AnnounceStatus = 24;//发电中
                }
                else
                {
                    announceList.AnnounceStatus = 23;//待发电
                    //announceList.AnnounceStatus = 24;//20200516暂时全部改成发电中
                }
                //更新字段
                announceList.RegisteredAbnormal = registeredAbnormal;
                announceList.RegisteredGenset = registeredGenset;
                announceList.RegisteredDtuId = registeredDtuId;
                announceList.GenerationFor = generationFor;
                announceList.RegisteredTime = DateTime.Now;
                announceList.IsReBinGenset = false;//初次签到默认false
                announceList.BinGensetNum = 1;//初次签到绑定油机台数为1
                announceList.IsChangeGenset = false;//初次签到默认false
                                                    //OQL updateQ = OQL.From(announceList).Update(announceList.AnnounceStatus, announceList.RegisteredAbnormal, announceList.RegisteredGenset, announceList.RegisteredDtuId, announceList.GenerationFor, announceList.RegisteredTime, announceList.IsReBinGenset, announceList.BinGensetNum).Where(c => c.Property(announceList.AnnounceCode) == announceCode).END;


                string[] upcolumn = new[] {
                    nameof(announceList.AnnounceStatus)
                    , nameof(announceList.RegisteredAbnormal)
                    , nameof(announceList.RegisteredGenset)
                    , nameof(announceList.RegisteredDtuId)
                    , nameof(announceList.GenerationFor)
                    , nameof(announceList.RegisteredTime)
                    , nameof(announceList.IsReBinGenset)
                    , nameof(announceList.BinGensetNum)
                };
                var isUpdateSuccess= _infoManager.UpdateAnnUpdateInclude(announceList, upcolumn);  
                if (isUpdateSuccess )
                {
                    result.Code = 1;
                    AnnounceStateXLog annlLog = new AnnounceStateXLog() { EventType = 3, CreatePerson = _workManager.CurrentUser.UserCode, CreatePersonName = _workManager.CurrentUser.UserName, CreateTime = DateTime.Now, RegisteredGenset = registeredGenset, RegisteredAbnormal = registeredAbnormal, PreState = 21, ToState = announceList.AnnounceStatus, AnnounceCode = announceCode, Latitude = latitude, Longitude = longitude, RegisteredDistance = registeredDistance };
                    // BllHelper.dbCxt.Add(annlLog);
                   await _infoManager.AddAnnounceStateXLog(annlLog);
                    
                }
                else
                {
                    result.Code = 0;//失败
                }

            }
            return result;
        }


        /// <summary>
        /// 计费方法
        /// </summary>
        /// <param name="AnnounceCode"></param>
        private async Task<bool> GetPowergenerationDataNotFgw(string AnnounceCode)
        {
           
            var item =await _infoManager.GetAnnFirstOrDefaultAsync(a => a.AnnounceCode == AnnounceCode);

            //已结单之前 只存id与code进AnnFee表
            if (item.AnnounceStatus < 29)
            {
                //var aaa = dbContext.Queryable<AnnFee>().First(a => a.AnnounceId == item.AnnounceId && a.AnnounceCode == item.AnnounceCode);
                var aaa = await _infoManager.GetAnnFeeFirstAsync(a => a.AnnounceId == item.AnnounceId && a.AnnounceCode == item.AnnounceCode);

                if (aaa == null)
                {
                    AnnFee annFee = new AnnFee()
                    {
                        AnnounceId = item.AnnounceId,
                        AnnounceCode = item.AnnounceCode
                    };
                    //存表

                    //int count = dbContext.Insertable(annFee).ExecuteCommand();
                    await _infoManager.AddAnnFeeFirstAsync(annFee);


                }
            }
            else
            {
                decimal FB = 0;//单价
                decimal P3 = Convert.ToDecimal(3.20);//油价基础费用
                decimal GenFeeTaxRate = 0;//税率
                decimal KWpower = 0;//发电量
                decimal LoadPeriod = 0;//带载
                decimal EmptyLoadPeriod = 0;//空载
                decimal RunningTotalPeriod = 0;//总运行时长
                decimal FBPrice = 0;//基础费用
                decimal FuelPrice = 0;//油耗费用
                decimal GenFee2 = 0;//发电费用
                decimal GenFeeTax = 0;//发电费用_含税
                decimal Distance = 0;//发电距离
                DateTime? GenStart = null;
                DateTime? GenStop = null;
                DataTable dt = new DataTable();
                DataTable dt2 = new DataTable();
                DataTable dt3 = new DataTable();
                //根据工单号去AnnounceGen表找所有发电记录
                // var annGenList = dbContext.Queryable<AnnounceGen>().Where(a => a.AnnounceId == item.AnnounceId && a.AnnounceCode == item.AnnounceCode).ToList();
                var annGenList = await _infoManager.GetAnnounceGenListAsync(a => a.AnnounceId == item.AnnounceId && a.AnnounceCode == item.AnnounceCode);

                if (annGenList != null && annGenList.Count > 0)
                {
                    string genRecordId = string.Join(",", annGenList.Select(a => a.GenRecordId).ToArray());

                    //dt = dbContext.Ado.UseStoredProcedure().GetDataTable("[USP_ComputeGenRecordValidGenFee]", new { genRecordIds = genRecordId });
                    dt = "[USP_ComputeGenRecordValidGenFee]".SqlProcedureQuery(new { genRecordIds = genRecordId });
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (dr["KWpower"] != null && dr["KWpower"].ToString() != "")
                                KWpower = KWpower + Convert.ToDecimal(dr["KWpower"]);
                            if (dr["LoadPeriod"] != null && dr["EmptyLoadPeriod"].ToString() != "")
                                LoadPeriod = LoadPeriod + Convert.ToDecimal(dr["LoadPeriod"]);
                            if (dr["EmptyLoadPeriod"] != null && dr["EmptyLoadPeriod"].ToString() != "")
                                EmptyLoadPeriod = EmptyLoadPeriod + Convert.ToDecimal(dr["EmptyLoadPeriod"]);
                            if (dr["Distance"] != null && dr["Distance"].ToString() != "")
                                Distance = Convert.ToDecimal(dr["Distance"]);
                        }
                        RunningTotalPeriod = LoadPeriod + EmptyLoadPeriod;
                    }
                    //求全部发电记录最小开始时间和最大停止时间
                    string sql = $"SELECT MIN(GenStart) AS GenStart,MAX(GenStop) AS GenStop FROM dbo.GenRecord WHERE GenRecordId IN({genRecordId})";
                    //dt2 = dbContext.Ado.GetDataTable(sql);
                    dt2 = await (sql).SqlQueryAsync();
                }
                //计算费用
                //计算单价
                //判断上级公司有无设置发电费用 有则直接找出基础费用单价FB,无则0
                var CompanyCode = item.AcceptCompanyCode.Substring(0, item.AcceptCompanyCode.Length - 4);
                string sqlC = $"SELECT ParaVal FROM dbo.CompanySetting WHERE CompanyCode='{CompanyCode}' AND	 ParaName='MtCompany_FB'";
                dt3 = await (sqlC).SqlQueryAsync();
                FB = dt3.Rows.Count != 0 ? Convert.ToDecimal(dt3.Rows[0]["ParaVal"]) : 0;
                //基础费用
                FBPrice = (item.BinGensetNum == 0 || item.BinGensetNum == null) ? FB : FB * (Convert.ToDecimal(1) + (Convert.ToDecimal(item.BinGensetNum) - Convert.ToDecimal(1)) * Convert.ToDecimal(0.5));
                if (annGenList != null && annGenList.Count > 0)//有发电记录才有时间
                {
                    GenStart = Convert.ToDateTime(dt2.Rows[0]["GenStart"]);
                    GenStop = Convert.ToDateTime(dt2.Rows[0]["GenStop"]);
                }
                //存表

                //var aaa = dbContext.Queryable<AnnFee>().First(a => a.AnnounceId == item.AnnounceId && a.AnnounceCode == item.AnnounceCode);
                var aaa = await _infoManager.GetAnnFeeFirstAsync(a => a.AnnounceId == item.AnnounceId && a.AnnounceCode == item.AnnounceCode);

                if (aaa == null)
                {
                    AnnFee annFee = new AnnFee
                    {
                        AnnounceId = item.AnnounceId,
                        AnnounceCode = item.AnnounceCode,
                        EmptyLoadPeriod = EmptyLoadPeriod,
                        LoadPeriod = LoadPeriod,
                        GenStart = GenStart,
                        GenStop = GenStop,
                        Distance = Distance,
                        RunningTotalPeriod = RunningTotalPeriod,
                        KWpower = KWpower,
                        FBPrice = FBPrice
                    };
                    // dbContext.Insertable(annFee).ExecuteCommand();
                    await _infoManager.AddAnnFeeFirstAsync(annFee);
                }
                else
                {
                    AnnFee annFee = new AnnFee
                    {
                        AnnFeeId = aaa.AnnFeeId,
                        AnnounceId = item.AnnounceId,
                        AnnounceCode = item.AnnounceCode,
                        EmptyLoadPeriod = EmptyLoadPeriod,
                        LoadPeriod = LoadPeriod,
                        GenStart = GenStart,
                        GenStop = GenStop,
                        Distance = Distance,
                        RunningTotalPeriod = RunningTotalPeriod,
                        KWpower = KWpower,
                        FBPrice = FBPrice
                    };
                    //dbContext.Updateable(annFee).ExecuteCommand();
                    await _infoManager.AddAnnFeeFirstAsync(annFee);
                }

            }

            return true;
        }
        #endregion

        #region 铁塔工单审核 用到的方法
        private async Task<DataTable> GetANNAuditbyAnnIds(List<string> annIds)
        {
            
                if (annIds == null || annIds.Count <= 0)
                    return null;
                //SELECT * FROM dbo.AnnounceAudit au LEFT JOIN dbo.AnnounceList a ON	au.AnnounceCode=a.AnnounceCode WHERE a.AnnounceId IN ('2313896')
                DataTable ann =await 
                    string.Format("SELECT * FROM dbo.AnnounceAudit au LEFT JOIN dbo.AnnounceList a ON	au.AnnounceCode=a.AnnounceCode WHERE a.AnnounceId IN ({0})  ",
                    (annIds.StrListToStr(","))).SqlQueryAsync();
                return ann;
           
        }


        private async Task<DataTable> GetANNbyAnnIds(List<string> annIds)
        {
            
                if (annIds == null || annIds.Count <= 0)
                    return null;
                DataTable ann = await
                    string.Format("SELECT AnnounceId,AnnounceCode,AnnounceStatus,GenDepartment,JobNumber,RegisteredGenset,BaseStationID,BaseStation,AcceptPersonCode,AnnouncePerson,GenerationFor FROM dbo.AnnounceList WHERE  AnnounceId IN ({0})  ",
                    (annIds.StrListToStr(","))).SqlQueryAsync();
                return ann;
            
        }

        public  int GetCompanyTypeIntByKeyStr(string keyStr)
        {
            if (string.IsNullOrEmpty(keyStr))
                return 0;
            if (keyStr.Contains("铁塔"))
                return 1;
            else if (keyStr.Contains("代维"))
                return 3;
            else if (keyStr.Contains("移动"))
                return 4;
            else if (keyStr.Contains("联通"))
                return 5;
            else if (keyStr.Contains("电信"))
                return 6;
            return 0;
        }
        public  List<int> GetCompanyTypeIntsByKeyStr(string keyStrs)
        {
            List<int> r = new List<int>();
            if (string.IsNullOrEmpty(keyStrs))
                return r;
            List<string> keystrs = keyStrs.StringSplitTirm(",").ToList();
            if (keystrs == null || keystrs.Count <= 0)
                return r;
            foreach (string s in keystrs)
            {
                int itmp = GetCompanyTypeIntByKeyStr(s);
                if (itmp > 0)
                    r.Add(itmp);
            }
            return r;
        }
        #endregion

    }
}
